package com.example.origin.demo.demo.blockqueue;

import lombok.SneakyThrows;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;

/**
 * 生产者、消费者缓冲区
 */
public class Storage1 {

    private final int maxSize = 10;
    private Queue<Object> queue = new LinkedList();

    @SneakyThrows
    public void put(Object obj) {
        synchronized (queue) {
            while (queue.size() >= maxSize) {
                System.out.println("缓冲区已满，不能进入");
                queue.wait();
            }

            queue.add(obj);
            System.out.println("进入缓冲区");
            queue.notifyAll();
        }
    }

    @SneakyThrows
    public Object get() {
        Object obj = null;
        synchronized (queue) {
            while (queue.size() <= 0) {
                System.out.println("缓冲区为空, 进入等待");
                queue.wait();
            }

            obj = queue.poll();
            System.out.println("离开缓冲区");
            queue.notifyAll();
        }

        return obj;
    }

    public static void main(String[] args) throws InterruptedException {
        Storage1 storage1 = new Storage1();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            storage1.get();
        }).start();

        for (int i = 0; i < 11; i++) {
            storage1.put(Integer.valueOf(1));
        }
    }
}